package com.kangjia.model.m0.service;

import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.kangjia.api.ParserReportService;
import com.kangjia.api.report.Advice;
import com.kangjia.api.report.Copy;
import com.kangjia.api.report.Health;
import com.kangjia.api.report.HealthIndex;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class PdfService {

	@Autowired
	private ProductService productService;
	// 设置字体样式
	private Font textFont = null; // 正常
	private Font redTextFont = null; // 正常,红色
	private Font boldFont8 = null; // 加粗

	public PdfService() {
		super();
		try {
			BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			textFont = new Font(bfChinese, 11, Font.NORMAL); // 正常
			redTextFont = new Font(bfChinese, 11, Font.NORMAL, BaseColor.RED); // 正常,红色
			boldFont8 = new Font(bfChinese, 8, Font.BOLD); // 加粗
		} catch (Exception e) {
			log.info("io e", e);
		}
	}

	public void createPdf(OutputStream os, String jsonNode, String inspectId, String name) {
		ParserReportService service = new ParserReportService(jsonNode, productService);
		Document document = new Document(PageSize.A4);
		try {
			PdfWriter.getInstance(document, os);
		} catch (Exception e) {
			log.info("io e", e);
		}
		document.open();
		document.newPage();

		createReport(document, name, service); // 门店信息
		createInfo(document, service); // 汇总信息
		createBase(document, service); // 基本信息
		createDetail(document, service); // 异常指标情况
		document.close();
	}
	
	

	private void createDetail(Document document, ParserReportService service) {
		try {
			Paragraph p = new Paragraph(
					"-------------------------------------------------------异常指标情况-------------------------------------------------------",
					textFont);
			p.setAlignment(Element.ALIGN_CENTER);
			document.add(p);
			List<HealthIndex> indexs = service.getThirdProm(true, false);
			PdfPTable table = null;
			PdfPCell cell = null;
			for (HealthIndex index : indexs) {
				table = new PdfPTable(new float[] { 0.2f, 0.7f });
				cell = new PdfPCell(new Paragraph("", textFont));
				cell.setBorder(0);
				cell.setVerticalAlignment(Element.ALIGN_LEFT);
				cell.setColspan(2);
				cell.setMinimumHeight(40);
				cell.setHorizontalAlignment(Element.ALIGN_LEFT);
				table.addCell(cell);
				cell = new PdfPCell(new Paragraph(index.getName(), textFont));
				cell.setBackgroundColor(BaseColor.GREEN);
				cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
				cell.setHorizontalAlignment(Element.ALIGN_CENTER);
				cell.setColspan(2);
				table.addCell(cell);
				cell = new PdfPCell(new Paragraph(getLevel(index.getAbnormalLevel()), textFont));
				cell.setBorderWidthRight(0);
				cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
				cell.setHorizontalAlignment(Element.ALIGN_LEFT);
				table.addCell(cell);
				cell = new PdfPCell(new Paragraph(getStand(index.getInspectStandard()), textFont));
				cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
				cell.setBorderWidthLeft(0);
				cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
				table.addCell(cell);
				cell = new PdfPCell(new Paragraph("【解释】", textFont));
				cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
				cell.setBorderWidthTop(0);
				cell.setBorderWidthBottom(0);
				cell.setVerticalAlignment(Element.ALIGN_LEFT);
				cell.setColspan(2);
				cell.setHorizontalAlignment(Element.ALIGN_LEFT);
				table.addCell(cell);
				cell = new PdfPCell(new Paragraph(index.getInspectExplain(), textFont));
				cell.setBorderWidthBottom(0);
				cell.setBorderWidthTop(0);
				cell.setVerticalAlignment(Element.ALIGN_LEFT);
				cell.setColspan(2);
				cell.setHorizontalAlignment(Element.ALIGN_LEFT);
				table.addCell(cell);
				int i = 1;
				if (index.getDiat() != null) {
					cell = new PdfPCell(new Paragraph("【膳食建议】", textFont));
					cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
					cell.setBorderWidthTop(0);
					cell.setBorderWidthBottom(0);
					cell.setVerticalAlignment(Element.ALIGN_LEFT);
					cell.setColspan(2);
					cell.setHorizontalAlignment(Element.ALIGN_LEFT);
					table.addCell(cell);
					for (Advice diat : index.getDiat()) {
						log.info(diat.getPersonalizedAdvice());
						if (StringUtils.isNoneBlank(diat.getPersonalizedAdvice())
								&& !"无".equalsIgnoreCase(diat.getPersonalizedAdvice())) {
							p = new Paragraph("(" + i++ + ")" + diat.getIndexName()
									+ diat.getPersonalizedAdvice().replaceAll("根据您的检测结果，", "，"), textFont);
							p.setAlignment(Element.ALIGN_LEFT);
							cell = new PdfPCell(p);
							cell.setBorderWidthTop(0);
							cell.setBorderWidthBottom(0);
							cell.setVerticalAlignment(Element.ALIGN_LEFT);
							cell.setColspan(2);
							cell.setHorizontalAlignment(Element.ALIGN_LEFT);
							table.addCell(cell);
						}
					}
				}
				i = 1;
				if (index.getNutrition() != null) {
					cell = new PdfPCell(new Paragraph("【营养建议】", textFont));
					cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
					cell.setBorderWidthTop(0);
					cell.setBorderWidthBottom(0);
					cell.setVerticalAlignment(Element.ALIGN_LEFT);
					cell.setColspan(2);
					cell.setHorizontalAlignment(Element.ALIGN_LEFT);
					table.addCell(cell);
					for (Advice diat : index.getNutrition()) {
						if (StringUtils.isNoneBlank(diat.getPersonalizedAdvice())
								&& !"无".equalsIgnoreCase(diat.getPersonalizedAdvice())) {
							p = new Paragraph("(" + i++ + ")" + diat.getIndexName()
									+ diat.getPersonalizedAdvice().replaceAll("根据您的检测结果，", "，"), textFont);
							p.setAlignment(Element.ALIGN_LEFT);
							cell = new PdfPCell(p);
							cell.setBorderWidthTop(0);
							cell.setBorderWidthBottom(0);
							cell.setVerticalAlignment(Element.ALIGN_LEFT);
							cell.setColspan(2);
							cell.setHorizontalAlignment(Element.ALIGN_LEFT);
							table.addCell(cell);
						}
					}
				}
				if (index.getMotion() != null) {
					cell = new PdfPCell(new Paragraph("【运动和生活方式建议】", textFont));
					cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
					cell.setBorderWidthTop(0);
					cell.setBorderWidthBottom(0);
					cell.setVerticalAlignment(Element.ALIGN_LEFT);
					cell.setColspan(2);
					cell.setHorizontalAlignment(Element.ALIGN_LEFT);
					table.addCell(cell);
					i = 1;
					for (Advice diat : index.getMotion()) {
						if (StringUtils.isNoneBlank(diat.getPersonalizedAdvice())
								&& !"无".equalsIgnoreCase(diat.getPersonalizedAdvice())) {
							p = new Paragraph("(" + i++ + ")" + diat.getIndexName()
									+ diat.getPersonalizedAdvice().replaceAll("根据您的检测结果，", "，"), textFont);
							p.setAlignment(Element.ALIGN_LEFT);
							cell = new PdfPCell(p);
							cell.setBorderWidthTop(0);
							cell.setBorderWidthBottom(0);
							cell.setVerticalAlignment(Element.ALIGN_LEFT);
							cell.setColspan(2);
							cell.setHorizontalAlignment(Element.ALIGN_LEFT);
							table.addCell(cell);
						}
					}
				}
				cell = new PdfPCell(new Paragraph("", textFont));
				cell.setBorderWidthTop(0);
				cell.setVerticalAlignment(Element.ALIGN_LEFT);
				cell.setColspan(2);
				cell.setHorizontalAlignment(Element.ALIGN_LEFT);
				table.addCell(cell);
				document.add(table);
			}
		} catch (DocumentException e) {

		}
	}

	private String getStand(String stand) {
		switch (stand) {
		case "2":
			return "偏高";
		default:
			return "偏低";
		}
	}

	private String getLevel(String lvl) {
		switch (lvl) {
		case "2":
			return "轻度";
		case "3":
		case "4":
			return "中度";
		default:
			return "重度";
		}
	}

	private void createBase(Document document, ParserReportService service) {
		try {
			Paragraph p = new Paragraph(
					"----------------------------------------------------------总体情况----------------------------------------------------------",
					textFont);
			p.setAlignment(Element.ALIGN_CENTER);
			document.add(p);
			PdfPTable table = new PdfPTable(new float[] { 0.2f, 0.7f, 0.1f });
			table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
			table.setLockedWidth(true);
			table.setTotalWidth(500);
			PdfPCell cell = new PdfPCell(new Paragraph("", textFont));
			cell.setBorder(0);
			cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell.setColspan(3);
			cell.setMinimumHeight(10);
			table.addCell(cell);
			Paragraph paragraph = new Paragraph("指标", textFont);
			cell = new PdfPCell(paragraph);
			cell.setBorderWidthTop(1);
			cell.setBorderWidthLeft(1);
			cell.setMinimumHeight(20);
			cell.setBackgroundColor(BaseColor.CYAN);
			cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			table.addCell(cell);
			paragraph = new Paragraph("名称解释", textFont);
			cell = new PdfPCell(paragraph);
			cell.setBorderWidthTop(1);
			cell.setBorderWidthLeft(1);
			cell.setMinimumHeight(20);
			cell.setBackgroundColor(BaseColor.CYAN);
			cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			table.addCell(cell);
			paragraph = new Paragraph("状态", textFont);
			cell = new PdfPCell(paragraph);
			cell.setBorderWidthTop(1);
			cell.setBorderWidthLeft(1);
			cell.setBorderWidthRight(1);
			cell.setMinimumHeight(20);
			cell.setBackgroundColor(BaseColor.CYAN);
			cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			table.addCell(cell);

			List<HealthIndex> indexs = service.getSecond(null, null, false, false, false);
			int i = 0;
			for (HealthIndex index : indexs) {
				paragraph = new Paragraph(index.getName(), textFont);
				cell = new PdfPCell(paragraph);
				cell.setBorderWidthTop(1);
				cell.setBorderWidthLeft(1);
				cell.setBackgroundColor(getColor(i));
				cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
				cell.setHorizontalAlignment(Element.ALIGN_CENTER);
				table.addCell(cell);
				paragraph = new Paragraph(index.getInspectExplain(), textFont);
				cell = new PdfPCell(paragraph);
				cell.setBorderWidthTop(1);
				cell.setBorderWidthLeft(1);
				cell.setBackgroundColor(getColor(i));
				cell.setVerticalAlignment(Element.ALIGN_LEFT);
				cell.setHorizontalAlignment(Element.ALIGN_LEFT);
				table.addCell(cell);
				paragraph = new Paragraph(getScore(index.getScore()), textFont);
				cell = new PdfPCell(paragraph);
				cell.setBorderWidthTop(1);
				cell.setBorderWidthLeft(1);
				cell.setBorderWidthRight(1);
				cell.setBackgroundColor(getColor(i));
				cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
				cell.setHorizontalAlignment(Element.ALIGN_CENTER);
				table.addCell(cell);
				i++;
			}
			List<Health> list = service.getHealth();
			for (Health health : list) {
				paragraph = new Paragraph(health.getName(), textFont);
				cell = new PdfPCell(paragraph);
				cell.setBorderWidthTop(1);
				cell.setBorderWidthLeft(1);
				cell.setBackgroundColor(getColor(i));
				cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
				cell.setHorizontalAlignment(Element.ALIGN_CENTER);
				table.addCell(cell);
				paragraph = new Paragraph(health.getInspectExplain(), textFont);
				cell = new PdfPCell(paragraph);
				cell.setBorderWidthTop(1);
				cell.setBorderWidthLeft(1);
				cell.setBackgroundColor(getColor(i));
				cell.setVerticalAlignment(Element.ALIGN_LEFT);
				cell.setHorizontalAlignment(Element.ALIGN_LEFT);
				table.addCell(cell);
				paragraph = new Paragraph(healthStatus(health), textFont);
				cell = new PdfPCell(paragraph);
				cell.setBorderWidthTop(1);
				cell.setBorderWidthLeft(1);
				cell.setBorderWidthRight(1);
				cell.setBackgroundColor(getColor(i));
				cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
				cell.setHorizontalAlignment(Element.ALIGN_CENTER);
				table.addCell(cell);
				i++;
			}
			cell = new PdfPCell(new Paragraph("", textFont));
			cell.setBorder(0);
			cell.setMinimumHeight(40);
			cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
			cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
			cell.setColspan(3);
			table.addCell(cell);
			document.add(table);
		} catch (DocumentException e) {

		}
	}

	private BaseColor getColor(int i) {
		if (i % 2 == 0) {
			return BaseColor.PINK;
		} else {
			return BaseColor.WHITE;
		}
	}

	private String getScore(String score) {
		Integer s = Integer.parseInt(score);
		if (s >= 95) {
			return "非常好";
		} else if (s >= 90 && s <= 94) {
			return "良好";
		} else if (s >= 85 && s <= 89) {
			return "轻度";
		} else if (s >= 80 && s <= 84) {
			return "中度";
		} else {
			return "重度";
		}

	}

	private String healthStatus(Health health) {
		String analysisResults = health.getAnalysisResults();
		if (StringUtils.isNotBlank(analysisResults)) {
			return analysisResults;
		} else {
			switch (health.getAbnormalLevel()) {
			case "1":
				return "非常好";
			case "2":
				return "良好";
			case "3":
				return "一般";
			default:
				return "差";
			}
		}
	}

	private void createReport(Document document, String name, ParserReportService service) {
		try {
			Paragraph p = new Paragraph();
			Phrase ph = new Phrase();
			Chunk chunk = new Chunk("报告编号:" + pad(3) + service.getSn(), boldFont8);
			chunk.setTextRise(10);
			ph.add(chunk);
			chunk = new Chunk(pad(40) + "创建时间:" + pad(3) + service.getInspectDate(), boldFont8);
			chunk.setTextRise(10);
			ph.add(chunk);
			chunk = new Chunk(pad(50) + "所属门店:" + pad(3) + name, boldFont8);
			chunk.setTextRise(10);
			ph.add(chunk);
			p.add(ph);
			document.add(p);
		} catch (DocumentException e) {

		}
	}

	private void createInfo(Document document, ParserReportService service) {
		try {
			Copy copy = service.getCopy();
			String name = service.getName();
			String nick = service.getNick();
			String ps = service.getPS();
			String age = service.getAge();
			String percentage = service.getPercentage();
			Map<String, String> strs = service.getServer();
			String abnormals = "0";
			String abnormalsSize = "";
			if (strs != null) {
				abnormals = strs.get("str"); // getAbnormals().replace("[", "").replace("]", "");
				abnormalsSize = strs.get("len"); // getAbnormalsSize();
			}

			String str = productService.getTemp("temp", "1");
			String[] s = str.split("<br>");
			Paragraph p = null;
			for (int i = 0; i < s.length; i++) {
				p = new Paragraph(getHealthSuggest(s[i], name, nick, ps, age, percentage, abnormals, abnormalsSize), textFont);
				p.setAlignment(Element.ALIGN_LEFT);
				document.add(p);
			}

			p = new Paragraph("膳食建议：", redTextFont);
			p.setAlignment(Element.ALIGN_LEFT);
			document.add(p);
			int i = 1;
			for (Advice diat : copy.getDiat()) {
				if (StringUtils.isNoneBlank(diat.getPersonalizedAdvice())
						&& !"无".equalsIgnoreCase(diat.getPersonalizedAdvice())) {
					p = new Paragraph("(" + i++ + ")" + diat.getIndexName()
							+ diat.getPersonalizedAdvice().replaceAll("根据您的检测结果，", "，"), textFont);
					p.setAlignment(Element.ALIGN_LEFT);
					document.add(p);
				}
			}
			p = new Paragraph("营养建议：", redTextFont);
			p.setAlignment(Element.ALIGN_LEFT);
			document.add(p);
			i = 1;
			for (Advice diat : copy.getNutrition()) {
				if (StringUtils.isNoneBlank(diat.getPersonalizedAdvice())
						&& !"无".equalsIgnoreCase(diat.getPersonalizedAdvice())) {
					p = new Paragraph("(" + i++ + ")" + diat.getIndexName()
							+ diat.getPersonalizedAdvice().replaceAll("根据您的检测结果，", "，"), textFont);
					p.setAlignment(Element.ALIGN_LEFT);
					document.add(p);
				}
			}
			p = new Paragraph("运动和生活建议：", redTextFont);
			p.setAlignment(Element.ALIGN_LEFT);
			document.add(p);
			i = 1;
			for (Advice diat : copy.getMotion()) {
				if (StringUtils.isNoneBlank(diat.getPersonalizedAdvice())
						&& !"无".equalsIgnoreCase(diat.getPersonalizedAdvice())) {
					p = new Paragraph("(" + i++ + ")" + diat.getPersonalizedAdvice(), textFont);
					p.setAlignment(Element.ALIGN_LEFT);
					document.add(p);
				}
			}
			p = new Paragraph("以上方案基于本次评估结果给予的健康改善建议，感谢您的阅读！由于个体差异并非所有建议都适用于您，请您根据实际情况进行合理的搭配选择。", textFont);
			p.setAlignment(Element.ALIGN_LEFT);
			p.setFirstLineIndent(23);
			document.add(p);
		} catch (DocumentException e) {

		}
	}

	private String getHealthSuggest(String str, String name, String nick, String ps, String age, String percentage,
			String abnormals, String abnormalsSize) {
		if (StringUtils.isNoneBlank(str)) {
			str = str.replace("#cname#", name).replace("#sex#", nick).replace("#healthStat#", ps)
					.replace("#age#", age).replace("#percentage#", percentage)
					.replace("#errorIndex#", abnormals).replace("#errorNum#", abnormalsSize);
		}
		return str;
	}

	public String pad(int i) {
		String space = "";
		for (int k = 0; k < i; k++) {
			space = " " + space;
		}
		return space;
	}

}
